#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @FileName  :fn_contract.py
# @Time      :2024/11/12 19:16
# @Author    :zhou_yi

import asyncio
from tools.units import DATETIME, CHART, FILE, Path
from models.Contract import InputContract, ContractCompany, OutContract
from service.fn_db import companyDB
from settings import Root


# 生成数据
async def contract_context(In: InputContract):
    start = In.start
    end = In.end
    service_date = f"自【{start.year}】年【{start.month}】月【{start.day}】日起至【{end.year}】年【{end.month}】月【{end.day}】止"
    months = DATETIME.month_diff(start, end)  # 月差
    price = In.signal_price * In.nums * months  # 总价
    up_price = CHART.rmb_upper(price)
    __A: dict = await companyDB.fetch_by_name(name=In.partA)
    __B: dict = await companyDB.fetch_by_name(name=In.partB)

    partA = ContractCompany(**__A)
    partB = ContractCompany(**__B)

    json_: dict = {
        'partA': partA,
        'partB': partB,
        'service_date': service_date,
        'service_local': In.service_local,
        'nums': f"{In.nums}",
        'signal_price': f"{In.signal_price:.2f}",
        'months': f"{months}",
        'price': f"{price:.2f}",
        'up_price': up_price
    }

    context = OutContract(**json_)
    return context


# 生成文件
async def file_contract(In: InputContract):
    filename = Path(Root) / f"tmp/{CHART.uid_key()}.docx"
    context = await contract_context(In)
    file_path = FILE.word_file(In.tpl, context.dict(), filename.__str__())
    download_name = f"服务合同_垃圾清运_{In.partA}.docx"
    return file_path, download_name


# 生成ByteIo对象
async def io_contract(In: InputContract):
    context = await contract_context(In)
    io_ = FILE.word_Io(In.tpl, context.dict())
    download_name = f"服务合同_垃圾清运_{In.partA}.docx"
    return io_, download_name


if __name__ == '__main__':
    _dic = {
        'tpl': "E:/py_code/prj_6/tpl/模版_服务合同_有害垃圾委托清运.docx",
        'partA': '北京市顺义区马坡第一幼儿园',
        'partB': '北京宏鑫汇能循环经济发展科技有限公司',
        'service_local': '北京市顺义区马坡第一幼儿园',
        'start': '2024-11-01',
        'end': '2025-07-31',
        'signal_price': 500.00,
        'nums': 10
    }

    _In = InputContract(**_dic)
    print(_In)

    R = asyncio.run(file_contract(_In))
    print(R)

    ...
